package com.itheima.jwttokendemo.Interceptor;

import com.itheima.jwttokendemo.service.UserService;
import com.itheima.jwttokendemo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter implements Filter {

    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 从 http 请求头中取出 token
        String token = httpRequest.getHeader("token");
        System.out.println("token:" + token);

        if (token != null) {
            String username = JwtUtil.getUserNameByToken(httpRequest);
            // 这边拿到的 用户名 应该去数据库查询获得密码，简略，步骤在service直接获取密码
            boolean result = JwtUtil.verify(token, username, userService.getPassword());
            if (result) {
                System.out.println("通过过滤器");
                chain.doFilter(request, response); // 放行请求
                return;
            }
        }
        System.out.println("过滤器拦截请求");
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 返回 401 状态码
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可以在这里进行一些初始化操作
    }

    @Override
    public void destroy() {
        // 销毁方法，可以在这里进行一些清理操作
    }
}
